package com.cloud.class05.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;

@Configuration
public class GatewayConfiguration {

    // 定义一个GatewayConfiguration类，用于配置网关相关的参数和处理器
    private final List<ViewResolver> viewResolvers; // 视图解析器列表
    private final ServerCodecConfigurer serverCodecConfigurer; // 服务器编解码器配置器

    // 构造函数，接收一个viewResolversProvider和一个serverCodecConfigurer作为参数
    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
        // 如果viewResolversProvider可用，则获取其提供的视图解析器列表，否则使用空列表
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        // 设置服务器编解码器配置器
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    // 定义一个Bean，用于创建SentinelGatewayBlockExceptionHandler实例
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // 注册Spring Cloud Gateway的阻塞异常处理器
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    // 定义一个Bean，用于创建GlobalFilter实例
    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    // 使用PostConstruct注解，表示在构造函数执行完毕后执行doInit方法
    @PostConstruct //javax.annotation.PostConstruct
    public void doInit() {
        // 初始化限流处理器
        initBlockHandler();
    }

    // 处理/自定义返回的例外信息
    private void initBlockHandler() {
        // 创建一个GatewayFlowRule集合
        Set<GatewayFlowRule> rules = new HashSet<>();
        // 添加一个限流规则，表示每秒最多允许2个请求通过
        rules.add(new GatewayFlowRule("pay_routh1").setCount(2).setIntervalSec(1));
        // 加载限流规则
        GatewayRuleManager.loadRules(rules);
        // 创建一个BlockRequestHandler实例
        BlockRequestHandler handler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
                // 创建一个Map用于存储错误信息
                Map<String, String> map = new HashMap<>();
                // 设置错误码为HTTP状态码429（Too Many Requests）的原因短语
                map.put("errorCode", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
                // 设置错误信息为"请求太过频繁，系统忙不过来，触发限流(sentinel+gataway整合Case)"
                map.put("errorMessage", "请求太过频繁，系统忙不过来，触发限流(sentinel+gataway整合Case)");
                // 设置响应状态码为429
                return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                        // 设置响应内容类型为JSON
                        .contentType(MediaType.APPLICATION_JSON)
                        // 设置响应体为map
                        .body(BodyInserters.fromValue(map));
            }
        };
        GatewayCallbackManager.setBlockHandler(handler); // 设置限流处理器
    }
}
 

 

